package com.ecommerce.order.controller;

import com.ecommerce.order.dto.OrderCreateRequest;
import com.ecommerce.order.dto.OrderPageResponse;
import com.ecommerce.order.dto.OrderResponse;
import com.ecommerce.order.dto.OrderUpdateStatusRequest;
import com.ecommerce.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 订单控制器
 */
@RestController
@RequestMapping("/api/orders")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     */
    @PostMapping
    public ResponseEntity<OrderResponse> createOrder(@Valid @RequestBody OrderCreateRequest request, HttpServletRequest httpRequest) {
        // 从请求属性中获取用户信息（由JwtAuthenticationFilter设置）
        String userId = (String) httpRequest.getAttribute("userId");
        String username = (String) httpRequest.getAttribute("username");
        
        log.info("创建订单请求 - 用户ID: {}, 用户名: {}, 请求数据: {}", userId, username, request);
        
        // 如果用户信息存在，则设置用户ID；否则使用匿名用户ID（用于测试和匿名下单）
        Long finalUserId;
        String finalUsername;
        if (userId != null && username != null) {
            finalUserId = Long.valueOf(userId);
            finalUsername = username;
            request.setUserId(finalUserId);
            log.info("使用认证用户创建订单 - 用户ID: {}, 用户名: {}", userId, username);
        } else {
            // 使用默认的匿名用户ID，或者从请求中获取临时用户ID
            Long anonymousUserId = request.getUserId() != null ? request.getUserId() : 1L; // 使用1L作为默认匿名用户ID
            finalUserId = anonymousUserId;
            finalUsername = "匿名用户";
            request.setUserId(finalUserId);
            log.info("使用匿名用户创建订单 - 用户ID: {}, 用户名: {}", anonymousUserId, finalUsername);
        }
        
        OrderResponse response = orderService.createOrder(request, finalUserId, finalUsername);
        log.info("订单创建成功 - 订单ID: {}, 用户ID: {}", response.getId(), request.getUserId());
        
        return ResponseEntity.status(HttpStatus.CREATED).body(response);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<OrderResponse> getOrderDetail(@PathVariable Long id, HttpServletRequest httpRequest) {
        try {
            String userId = (String) httpRequest.getAttribute("userId");
            String username = (String) httpRequest.getAttribute("username");
            
            log.info("获取订单详情 - 订单ID: {}, 用户ID: {}", id, userId);
            
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            
            OrderResponse response = orderService.getOrderById(id, Long.valueOf(userId));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取用户订单列表（分页）
     */
    @GetMapping
    public ResponseEntity<OrderPageResponse> getUserOrders(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest httpRequest) {
        try {
            String userId = (String) httpRequest.getAttribute("userId");
            String username = (String) httpRequest.getAttribute("username");
            
            log.info("获取用户订单列表 - 用户ID: {}, 页码: {}, 大小: {}", userId, page, size);
            
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            
            OrderPageResponse orders = orderService.getOrdersByUserId(Long.valueOf(userId), page, size);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            log.error("获取用户订单列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 根据状态获取用户订单列表
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<OrderPageResponse> getUserOrdersByStatus(
            @PathVariable String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest httpRequest) {
        try {
            String userId = (String) httpRequest.getAttribute("userId");
            String username = (String) httpRequest.getAttribute("username");
            
            log.info("根据状态获取用户订单列表 - 用户ID: {}, 状态: {}, 页码: {}, 大小: {}", userId, status, page, size);
            
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            
            OrderPageResponse orders = orderService.getOrdersByUserIdAndStatus(Long.valueOf(userId), Integer.valueOf(status), page, size);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            log.error("根据状态获取用户订单列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新订单状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<OrderResponse> updateOrderStatus(
            @PathVariable Long id,
            @RequestParam Integer status,
            HttpServletRequest httpRequest) {
        try {
            String userId = (String) httpRequest.getAttribute("userId");
            String username = (String) httpRequest.getAttribute("username");
            
            log.info("更新订单状态 - 订单ID: {}, 用户ID: {}, 新状态: {}", id, userId, status);
            
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            
            // 创建状态更新请求对象
            OrderUpdateStatusRequest updateRequest = new OrderUpdateStatusRequest();
            updateRequest.setStatus(status);
            
            OrderResponse response = orderService.updateOrderStatus(id, updateRequest, Long.valueOf(userId));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新订单状态失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 取消订单
     */
    @PutMapping("/{id}/cancel")
    public ResponseEntity<OrderResponse> cancelOrder(@PathVariable Long id, HttpServletRequest httpRequest) {
        try {
            String userId = (String) httpRequest.getAttribute("userId");
            String username = (String) httpRequest.getAttribute("username");
            
            log.info("取消订单 - 订单ID: {}, 用户ID: {}", id, userId);
            
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            
            OrderResponse response = orderService.cancelOrder(id, Long.valueOf(userId));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteOrder(@PathVariable Long id, HttpServletRequest httpRequest) {
        try {
            String userId = (String) httpRequest.getAttribute("userId");
            String username = (String) httpRequest.getAttribute("username");
            
            log.info("删除订单 - 订单ID: {}, 用户ID: {}", id, userId);
            
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            
            orderService.deleteOrder(id, Long.valueOf(userId));
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            log.error("删除订单失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 支付订单
     */
    @PostMapping("/{id}/pay")
    public ResponseEntity<OrderResponse> payOrder(
            @PathVariable Long id,
            @RequestBody Map<String, Object> payload,
            HttpServletRequest httpRequest) {
        try {
            String userId = (String) httpRequest.getAttribute("userId");
            String username = (String) httpRequest.getAttribute("username");
            
            Integer paymentMethod = null;
            if (payload != null && payload.containsKey("paymentMethod")) {
                Object method = payload.get("paymentMethod");
                if (method instanceof Integer) {
                    paymentMethod = (Integer) method;
                } else if (method instanceof String) {
                    paymentMethod = Integer.parseInt((String) method);
                }
            }
            
            log.info("支付订单 - 订单ID: {}, 用户ID: {}, 支付方式: {}", id, userId, paymentMethod);
            
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            
            if (paymentMethod == null) {
                return ResponseEntity.badRequest().build();
            }
            
            OrderResponse response = orderService.payOrder(id, paymentMethod, Long.valueOf(userId));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("支付订单失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public ResponseEntity<String> test() {
        return ResponseEntity.ok("Order service is running");
    }
    
    @PostMapping("/test-post")
    public ResponseEntity<String> testPost(@RequestBody String data) {
        return ResponseEntity.ok("POST request received: " + data);
    }
}